package com.blobfish.fiction.common.base.interceptor;

import cn.hutool.core.util.StrUtil;
import com.blobfish.fiction.common.base.exception.GlobalErrorException;
import com.blobfish.fiction.common.base.model.QmResult;
import com.blobfish.fiction.common.util.ValiMessageUtil;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.kit.PropKit;
import com.jfinal.log.Log;

import java.util.Enumeration;

/**
 * 统一异常处理器
 *
 * @author huangbo
 */
public class ErrorInterceptor implements Interceptor {
    private static final Log log = Log.getLog(ErrorInterceptor.class);

    @Override
    public void intercept(Invocation invocation) {
        try {
            invocation.invoke();
        } catch (GlobalErrorException e) {
            QmResult qmResult = new QmResult();
            qmResult.setCode(500);
            String errKey = e.getId();
            String errMsg = PropKit.use("message.txt").get(errKey);
            if (StrUtil.isBlank(errMsg)) {
                errMsg = StrUtil.format("can not find key:[{}] on message.txt!", errKey);
                log.error(errMsg);
            }
            qmResult.setMsgId(errKey);
            qmResult.setMsg(errMsg);
            invocation.getController().renderJson(qmResult);
            log.error(e.getMessage());
        } catch (Exception e) {
            QmResult result = new QmResult();
            result.setMsg(e.getMessage() == null ? "系统异常" : e.getMessage());
            result.setCode(500);
            invocation.getController().renderJson(result);
            log.error(e.getMessage());
        }
    }
}
